package com.github.shiqiyue.app.config.captcha;

import com.google.code.kaptcha.Producer;
import org.apache.commons.codec.binary.Base64;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/***
 * 验证码服务-kaptcha实现
 * @author wenyao.wu
 * @since 2020年4月26日
 */
public class KaptchaServiceImpl implements ICaptchaService {

    private Producer captchaProducer;

    /***
     * 生成验证码
     * @return
     */
    @Override
    public String generateCaptcha() {
        return captchaProducer.createText();
    }

    /***
     * 获取图形验证码 base64格式
     * @return
     * @throws IOException
     */
    @Override
    public String generateBase64(String text) throws IOException {
        ByteArrayOutputStream bs = generateOutputStream(text);
        return Base64.encodeBase64String(bs.toByteArray());
    }

    /***
     * 获取图形验证码，流格式
     * @param text
     * @return
     * @throws IOException
     */
    @Override
    public ByteArrayOutputStream generateOutputStream(String text) throws IOException {
        BufferedImage bi = captchaProducer.createImage(text);
        ByteArrayOutputStream bs;
        bs = new ByteArrayOutputStream();
        ImageIO.write(bi, "png", bs);
        return bs;
    }

    public void setCaptchaProducer(Producer captchaProducer) {
        this.captchaProducer = captchaProducer;
    }
}
